package cn.zhaoyuening.zhaocloud.provider.register.impl;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.TreeSet;
import java.util.logging.Logger;

import cn.zhaoyuening.zhaocloud.common.bean.CloudServiceBean;
import cn.zhaoyuening.zhaocloud.common.bean.CloudServiceRegisterBean;
import cn.zhaoyuening.zhaocloud.common.utils.JsonUtils;
import cn.zhaoyuening.zhaocloud.provider.register.CloudServiceRegister;

public class BaseCloudServiceRegister implements CloudServiceRegister{
	private Logger log = Logger.getLogger(this.getClass().getName());
	//服务暴露的端口
	private Integer port;
	//服务注册中心地址
	private String registryHost;
	//服务注册中心端口
	private Integer registryPort;
	
	public BaseCloudServiceRegister(Integer port, String registryHost, Integer registryPort) {
		this.port = port;
		this.registryHost = registryHost;
		this.registryPort = registryPort;
	}	


	public void registryService(final TreeSet<CloudServiceBean> serviceSet) {
		new Thread(new Runnable() {
			public void run() {
				int count = 0;
				boolean registrySuccess = false;
				while(!registrySuccess&&count<=3){
					registry(serviceSet);
					count++;
				}
				if(registrySuccess){
					log.info("注册服务成功");
				}else{
					log.warning("注册服务失败");
				}
			}
		}).start();
		
	}
	
	private boolean registry(TreeSet<CloudServiceBean> serviceSet){
		//封装 端口号与注册的服务列表
		CloudServiceRegisterBean registerBean = new CloudServiceRegisterBean(port, serviceSet);
		try {
			Socket socket = new Socket(registryHost, registryPort);
			ObjectOutputStream objOut = new ObjectOutputStream(socket.getOutputStream());
			ObjectInputStream objIn = new ObjectInputStream(socket.getInputStream());
			String registerJson = JsonUtils.objectToJson(registerBean);
			objOut.writeUTF(registerJson );
			String result = objIn.readUTF();
			if(result!=null&&result.equals("success")){
				return true;
			}
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
		}
		return false;
	}

	

	public Integer getPort() {
		return port;
	}

	public void setPort(Integer port) {
		this.port = port;
	}

	public String getRegistryHost() {
		return registryHost;
	}

	public void setRegistryHost(String registryHost) {
		this.registryHost = registryHost;
	}

	public Integer getRegistryPort() {
		return registryPort;
	}

	public void setRegistryPort(Integer registryPort) {
		this.registryPort = registryPort;
	}


	public void registryService(Class<?> serviceClass, int version) {
		
	}


	public void registryService(String serviceName, int version) {
		
	}


	public void removeService(Class<?> serviceClass, int version) {
		
	}


	public void removeService(String serviceName, int version) {
		
	}


	public void closeAllService() {
		// TODO Auto-generated method stub
		
	}


	
	
}
